Substrings¶

🎨 replace¶

In [2]:
'I applied to UofU'.replace('UofU', 'BYU')
Out[2]:
'I applied to BYU, and BYU'

replace let's you replace a substring with another string.

In [3]:
'A normal looking phrase'.replace(' ', '-')
Out[3]:
'A-normal-looking-phrase'

By default, replace replaces all occurrences of the substring with its substitute.

In [12]:
'I like cats and cats'.replace('cats', 'dogs', 1)
Out[12]:
'I like dogs and cats'

You can provide a 3rd argument to replace to control how many substitutions can be made.

In [22]:
text = 'I like to eat pizza'
new_text = text.replace('pizza', 'soup')
print(text)
print(new_text)
I like to eat pizza
I like to eat soup

replace (and any other string function that returns a string) returns a new string.

It doesn't modify the input string.

🎨 in¶

In [23]:
'BYU' in 'I am a student at BYU.'
Out[23]:
True
In [24]:
'BYU' in 'This room is full of monkeys!'
Out[24]:
False

Use the in operator to determine whether a substring is present in a string.

🖌 Custom Character Classes¶

In [25]:
def is_vowel(letter):
    return letter in 'AEIOUaeiou'
In [26]:
found = ''
for letter in 'The Aeneid is ancient Greek literature.':
    if is_vowel(letter):
        found += letter
print(found)
eAeeiiaieeeieaue
In [27]:
def is_vowel(letter):
    return letter.lower() in 'aeiou'

found = ''
for letter in 'The Aeneid is ancient Greek literature.':
    if is_vowel(letter):
        found += letter
print(found)
eAeeiiaieeeieaue

🧑🏽‍🎨 BYU Enthusiasts¶

Capitalize every letter in an input string that is part of BYU.

In [28]:
def byu(text):
    """Capitalize every letter of `text` that is part of 'BYU'"""
    result = ''
    for char in text:
        if char in 'byu':
            char = char.upper()
        result += char
    return result
In [ ]:
def byu(text):
    """Capitalize every letter of `text` that is part of 'BYU'"""
    result = ''
    for c in text:
        if c in 'byu':
            result += c.upper()
        else:
            result += c
    return result
In [31]:
print(byu('write "byu" in all-caps. By byu!'))
write "BYU" in all-caps. BY BYU!
In [32]:
print(byu('Any student, boy or girl, young or old, can be a yodeler.'))
AnY stUdent, BoY or girl, YoUng or old, can Be a Yodeler.

🖌 Early-return¶

In [34]:
def is_bracket(letter):
    return letter in '{}[]<>'

def has_brackets(text):
    for letter in text:
        if is_bracket(letter):
            return True
    return False
In [35]:
has_brackets('Just some words')
Out[35]:
False
In [36]:
has_brackets('A Python list prints like this: [1, 2, 3, 4]')
Out[36]:
True

👨🏼‍🎨 Odd Numbers¶

Write a function that indicates whether a string has odd-numbered digits in it.

In [37]:
def is_odd_digit(letter):
    return letter in '13579'

def has_odds(text):
    """Return True if the text has odd-numbered digits"""
    for letter in text:
        if is_odd_digit(letter):
            return True
    return False
In [ ]:
def is_odd_digit(letter):
    return letter in '13579'

def has_odds(text):
    """Return True if the text has odd-numbered digits"""
    for letter in text:
        if is_odd_digit(letter):
            return True
    return False
In [38]:
has_odds('I have 2 apples to share with 4 people.')
Out[38]:
False
In [40]:
has_odds('I have 2 apples, and there are 34 people, but I will eat them all!')
Out[40]:
True

👩🏼‍🎨 True Blue¶

Write a function that indicates whether a text has any of the following substrings in it:

  • BYU
  • blue
  • cougar
In [53]:
def is_true_blue(text):
    """Returns True if `text` contains any of: 'BYU', 'blue', or 'cougar'"""
    for true_blue_term in ['BYU', 'blue', 'cougar']:
        print(true_blue_term)
        if true_blue_term in text:
            print('found it!')
            return True
    return False
In [54]:
is_true_blue('My friend goes to UVU')
BYU
blue
cougar
Out[54]:
False
In [55]:
is_true_blue('I love BYU!')
BYU
found it!
Out[55]:
True
In [56]:
is_true_blue('The sky is blue')
BYU
blue
found it!
Out[56]:
True

🎨 in and list¶

In [57]:
def is_suspect(person):
    return person in ['John', 'Jane', 'Susan', 'Carlos', 'Kathy', 'Morgan']

def identify_suspects(people):
    suspects = []
    for person in people:
        if is_suspect(person):
            suspects.append(person)
    return suspects
In [58]:
students = ['George', 'Hannah', 'Kathy', 'Michael', 'John']
print(identify_suspects(students))
['Kathy', 'John']
In [59]:
neighbors = ['Carl', 'Brooke', 'Jane', 'Jarom', 'Sally', 'John', 'Mike']
print(identify_suspects(neighbors))
['Jane', 'John']

Are there any suspected neighbors that are also suspected students?

In [ ]:
def find_key_suspects(students, neighbors):
    """Identify persons who are both students and neighbors and are suspect"""
    
In [ ]:
def find_key_suspects(students, neighbors):
    suspected_students = identify_suspects(students)
    suspected_neighbors = identify_suspects(neighbors)
    
    key_suspects = []
    for person in suspected_neighbors:
        if person in suspected_students:
            key_suspects.append(person)
    return key_suspects
In [ ]:
def filter_to(population, group):
    keepers = []
    for item in population:
        if item in group:
            keepers.append(item)
    return keepers

def find_key_suspects(students, neighbors):
    student_neighbors = filter_to(students, neighbors)
    key_suspects = identify_suspects(student_neighbors)
    return key_suspects
In [ ]:
find_key_suspects(students, neighbors)

Key Ideas¶

  • substrings
  • replace
  • in
  • Custom character classes using in
  • Early-return pattern
  • in and list